<!-- 登录 -->
<template>
  <view class="about">
    <canvas
      canvas-id="bubble"
      :style="'width:' + width + 'px;height:' + height + 'px'"
      class="like-fx"
    ></canvas>
    <like-fx ref="likeFx" :width="width" :height="height"></like-fx>

    <view class="login-box">
      <view class="cu-bar bg-white margin-top-xs">
        <view class="action sub-title">
          <text class="title-inner">OSCE-管理平台</text>
          <text class="text-ABC text-blue">curriculum</text>
        </view>
      </view>
      <u--form :model="loginForm" ref="uForm" :rules="loginFormRules">
        <u-form-item prop="username">
          <u--input
            v-model="loginForm.username"
            placeholder="手机号"
            prefixIcon="phone-fill"
            prefixIconStyle="font-size: 22px;color: #909399"
          ></u--input>
        </u-form-item>
        <u-form-item prop="password">
          <u--input
            v-model="loginForm.password"
            placeholder="密码"
            type='password'
            prefixIcon="lock-fill"
            prefixIconStyle="font-size: 22px;color: #909399"
          ></u--input>
        </u-form-item>
      </u--form>
      <view style="padding: 10px 0;">
        <u-button type="primary" @click="submit" :loading="btnLoading">登 录</u-button>
      </view>
      
    </view>
    <view class="pos">
      <view @click="downLoadHandle">下载最新版本app</view>
    </view>
    <quick-message ref="message"></quick-message>
    <view>
      <u-modal :show="chooseShow" title="请先选择体检" width='400' confirm-color='#00796B' @confirm="chooseHandle">
        <view class="choose-box">
          <view v-for="(item,index) in chooseList" :key="index" :class="'choose-inner ' + (item.id == chooseInspectId ? 'isChoose':'')" >
            <view class="choose-left" @tap="chooseBoxHandle(item)"></view>
            <view class="choose-content" @tap="chooseBoxHandle(item)">
              {{ item.nameBak }}
            </view>
          </view>
          <!-- <u-radio-group
            v-model="chooseInspectId"
            placement="column"
          >
            <u-radio
              :customStyle="{marginBottom: '8px'}"
              v-for="(item, index) in chooseList"
              :key="index"
              :label="item.nameBak"
              :name="item.id"
            >
            </u-radio>
          </u-radio-group> -->
        </view>
      </u-modal>
    </view>
    <view>
      <u-modal :show="loadingShow" title="apk下载中" :showConfirmButton="false" :showCancelButton="false" width="400px">
        <view class="slot-content">
          <view style="color: #333;display:flex;align-items: center;justify-content: center;padding: 2px 0 10px 0;font-size: 14px;">({{ totalBytesWritten }}/ {{ totalBytesExpectedToWrite }})下载中...</view>
          <ProgressBar :Width="progress" Type="candy" :Vice="true"></ProgressBar>
        </view>
      </u-modal>
    </view>
    <view class="versonBox">
      <view class="inner">
        <view>当前版本号：</view>
        <view style='padding-right: 10px'>{{ versionCodeCurrent }}</view>
        <view> 最新版本号：</view>
        <view>{{ versionCodeNew }}</view>
        <view style='color: transparent;font-size: 2px;'>{{ flag }}</view>
      </view>
      <!-- <view class="downLoad" v-if=" versionCodeNew !== versionCodeCurrent" @click='getVer'>已检测到新版本，请点击下载</view> -->
    </view>
  </view>
</template>
<script>
import LikeFx from "@/components/likeFx/likeFx.vue";
import ProgressBar from '@/components/Progress-Bar/Progress-Bar';
import mRequest from '@/api/index.js'
import hccmStore from '@/common/hccm-store.js'
import manifest from '@/manifest.json'
import hccmConfig from '@/common/hccm-config.js'
export default {
  components: {
    LikeFx,
    ProgressBar
  },
  data() {
    return {
      animation_timer: null, // 动画定时器
      msgShow: false,
      btnLoading: false,
      chooseShow: false,
      chooseList:[],
      chooseInspectId:'',
      btnTitle: '登 录',
      width: 375,
      height: 1920,
      loginForm: {
      username: '',
          password: '',
      // username: '13022222201',
      //       password: '2201',
			},
			loginFormRules: {
				username: [
					{
						required: true,
						message: '请输入手机号',
						trigger: ['blur', 'change']
					}
				],
				password: [
					{
						required: true,
						message: '请输入密码',
						trigger: ['blur', 'change']
					}
				],
			},
      loadingShow: false,
      progress: 0,
      totalBytesWritten: '',
      totalBytesExpectedToWrite: '',

      versionName: '加载中',
      versionCodeCurrent: 0,
      versionCodeNew: 0,
      progress: 0,
      flag: null,
      aaaa: '1212',
    };
  },
  onLoad() {
    this.getVer()
    this._startLikeAnimation();
    if(hccmStore.getChooseInspectId()){
      uni.reLaunch({
        url: 'pages/home/index'
      })
    }
  },
  methods: {
    chooseBoxHandle(val){
      console.log(val)
      this.chooseInspectId = val.id
    },
    // 选择体检
    chooseHandle(){
      if(!this.chooseInspectId){
        this.$refs.message.show({
          type:'warning', //String 默认default
          msg:'请先选择体检', //String 显示内容 *
          direction:'top', //String 默认顶部显示
          icon:true, //Boolean|String 显示icon(false/true/string 默认显示icon)
          mask:true, //Boolean 遮罩（默认false没有遮罩）
          time:2000, //Number|Boolean 默认3000/false为不自动关闭
          customStyle:{ //自定义样式
            // color:'#FFFFFF', //字体图标色
            // backgroundColor:'rgba(0,0,0,.5)', //背景色
            fontSize: 12,
          }, 
          iconSize: 16, //Number 自定义icon大小(单位px 默认16 设置后会覆盖自定义样式里的设置优先级最高)
          iconColor: '', //String icon颜色(默认主题颜色 设置后会覆盖自定义样式里的设置优先级最高)
        })
      }else{
        hccmStore.setChooseInspectId(this.chooseInspectId)
        uni.reLaunch({
          url: '/pages/home/index'
        })
      }
    },
    // 获取体检列表
    getInspectList(){
      mRequest.getRealTimeData({
        recordsTeacherId: hccmStore.getUser().teacherId,
      }).then(res=>{
        this.chooseList = res.data.records
        this.chooseList.map(item=>{
          item.nameBak = `${item.name}(${item.school})`
        })
        setTimeout(()=>{
          this.chooseShow = true
        },500)
      })
    },
    submit(){
      this.$refs.uForm.validate().then(res => {
        this.btnLoading = true
        this.btnTitle = '登录中...'
        console.log(res)
        mRequest.loginByMobile({
          mobile: this.loginForm.username,
          password: this.loginForm.password
        }).then(res=>{
          hccmStore.setPhoneToken(res.token)
          hccmStore.setUserPhone(this.loginForm.username)
          if(res.recordsId){
            hccmStore.setJudge(res.recordsId)
          }else{
            hccmStore.setJudge('false')
          }
          hccmStore.setUser(res.userInfo)
          this.$refs.message.show({
            type:'success', //String 默认default
            msg:'登录成功！', //String 显示内容 *
            direction:'top', //String 默认顶部显示
            icon:true, //Boolean|String 显示icon(false/true/string 默认显示icon)
            mask:true, //Boolean 遮罩（默认false没有遮罩）
            time:1000, //Number|Boolean 默认3000/false为不自动关闭
            customStyle:{ //自定义样式
              // color:'#FFFFFF', //字体图标色
              // backgroundColor:'rgba(0,0,0,.5)', //背景色
              fontSize: 12,
            }, 
            iconSize: 16, //Number 自定义icon大小(单位px 默认16 设置后会覆盖自定义样式里的设置优先级最高)
            iconColor: '', //String icon颜色(默认主题颜色 设置后会覆盖自定义样式里的设置优先级最高)
          })
          this.btnLoading = false
          this.btnTitle = '登 录'
          // this.getInspectList()
          setTimeout(() => {
            uni.reLaunch({
              url: '/pages/home/index'
            })
          }, 1000);
          return
          setTimeout(() => {
            uni.reLaunch({
              url: 'pages/home/index'
            })
          }, 1000);
        }).catch(err=>{
          this.btnLoading = false
          this.btnTitle = '登 录'
        })
      }).catch(errors => {
        this.$refs.message.show({
          type:'default', //String 默认default
          msg:'校验不通过', //String 显示内容 *
          direction:'top', //String 默认顶部显示
          icon:true, //Boolean|String 显示icon(false/true/string 默认显示icon)
          mask:true, //Boolean 遮罩（默认false没有遮罩）
          time:2000, //Number|Boolean 默认3000/false为不自动关闭
          customStyle:{ //自定义样式
            // color:'#FFFFFF', //字体图标色
            // backgroundColor:'rgba(0,0,0,.5)', //背景色
            fontSize: 12,
          }, 
          iconSize: 16, //Number 自定义icon大小(单位px 默认16 设置后会覆盖自定义样式里的设置优先级最高)
          iconColor: '', //String icon颜色(默认主题颜色 设置后会覆盖自定义样式里的设置优先级最高)
        })
      })
    },
    tap() {
      uni.reLaunch({
        url: "/pages/example/components"
      });
    },
    _startLikeAnimation() {
      this.animation_timer = setInterval(() => {
        // this.$refs.likeFx.likeClick();
      }, 300);
    },
    getVer () {
      // #ifdef APP-PLUS
      let _this = this
      plus.runtime.getProperty(plus.runtime.appid, function(wgtInfo) {
        _this.versionName = wgtInfo.version
        _this.versionCodeCurrent =  Number(wgtInfo.versionCode)
        console.log('versionCodeCurrent', _this.versionCodeCurrent)
        console.log('应用名称：' + wgtInfo.name);
        console.log('应用描述：' + wgtInfo.description);
        console.log('应用ID：' + wgtInfo.appid);

        // 获取最新的版本号
        mRequest.getVersion().then(res => {
          if (res.code === 0){
            console.log(res.padversion.versionNo)
            _this.versionCodeNew = res.padversion.versionNo
            _this.flag  = Number(res.padversion.versionNo) > _this.versionCodeCurrent
            if (Number(res.padversion.versionNo) > _this.versionCodeCurrent) {
              uni.showModal({
                title: '有新版本',
                content: '请先下载并更新',
                // showCancel: false,
                success: r => {
                  if (r.confirm) {
                    _this.downLoadHandle()
                  }
                }
              });
            }
          }
          // console.log(res.versionNo,'resssss=>')
        })
      });
      // #endif
    },
    downLoadHandle() {
      this.loadingShow = true
      // TODO 需要更新下载地址
      let item = {
        fileUrl: `${hccmConfig.HCCM_HOST_URL}/osceversion/osce-app.apk`
      }
      let fileUrl = item.fileUrl
      // 下载方式一：
      // plus.runtime.openURL(fileUrl)
      // this.isShowProgress = true;
      console.log(fileUrl)
      // 下载方式二：
      const downloadTask = uni.downloadFile({
        url: fileUrl,
        success: (res) => {
          const filePath = res.tempFilePath;
          console.log('res======>下载成功', res)
          if (res.statusCode === 200) {
            // this.isShowProgress = false;
            console.log('下载成功');
          }
          uni.saveFile({
            tempFilePath: filePath,
            success: (res1) => {
              // this.isShowProgress = false;
              var saveFilePath = res1.savedFilePath;
              uni.showModal({
                title: "提示",
                content: "文件已保存：" + saveFilePath,
                cancelText: "我知道了",
                confirmText: "打开文件",
                success: (res2) => {
                  if (res2.confirm) {
                    uni.openDocument({
                      filePath: saveFilePath,
                      success: (res) => {
                        console.log("打开文档成功", JSON.stringify(res))
                      }
                    })
                  }
                }
              })
            }
          })
        }
      })
      let _this = this
      downloadTask.onProgressUpdate((res) => {
        // console.log('下载进度' + res.progress);
        _this.progress = res.progress;
        function fns(val) {
          if (val === 0) return "0 B"
          var k = 1024;
          var sizes = ['B', 'KB', 'MB', 'GB', 'PB', 'TB', 'EB', 'ZB', 'YB'],
            i = Math.floor(Math.log(val) / Math.log(k));
          return (val / Math.pow(k, i)).toPrecision(3) + "" + sizes[i]
        }
        function fn(val) {
          if (val === 0) return "0 B"
          var k = 1024;
          var sizes = ['B', 'KB', 'MB', 'GB', 'PB', 'TB', 'EB', 'ZB', 'YB'],
            i = Math.floor(Math.log(val) / Math.log(k));
          return (val / Math.pow(k, i)).toPrecision(3) + "" + sizes[i]
        }
        _this.totalBytesWritten = fns(res.totalBytesWritten)
        _this.totalBytesExpectedToWrite = fn((res.totalBytesExpectedToWrite))
        // console.log('_this.totalBytesWritten',_this.totalBytesWritten)
        // console.log('_this.totalBytesExpectedToWrite',_this.totalBytesExpectedToWrite)
        if(_this.progress === 100){
          console.log(_this.progress)
          _this.loadingShow = false
        }
        // 满足测试条件，取消下载任务。
        // if (_this.progress == 100) {
        // 	console.log('下载完成')
        // 	downloadTask.abort();
        // }
      });
    }
  }
};
</script>

<style scoped lang='scss'>
.choose-box{
  min-height: 260px;
  max-height: 600px;
  font-size: 16px;
  color: #333;
  width: 100%;
  padding: 0 20px;
  .choose-inner{
    padding: 10px 0;
    display: flex;
    align-items: center;
    .choose-left{
      border: 2px solid #f5f5f5;
      height: 14px;
      width: 14px;
      border-radius: 14px; 
      margin-right: 6px;
      margin-top: 2px;
    }
    .choose-content{
      flex: 1;
    }
  }
  .isChoose{
    color: #00796B;
    .choose-left{
      border: 2px solid #00796B;
      position: relative;
    }
    .choose-left::before{
      content: '';
      position: absolute;
      top: 4px;
      left: 4px;
      width: 6px;
      height: 6px;
      border-radius: 100%;
      background: #00796B;

    }
  }
}
.about {
  margin: 0;
  width: 100%;
  height: 100vh;
  // padding-top: 20%;
  color: #fff;
  background: linear-gradient(-120deg, #6200EA, #304FFE, #26A69A, #00C853);
  // background: linear-gradient(-120deg, #f15bb5, #9a5ce5, #01beff, #00f5d4);
  /* background: linear-gradient(-120deg, #0976ea, #c471f5, #f956b6, #ea7e0a); */
  background-size: 500% 500%;
  animation: gradientBG 15s ease infinite;
  display: flex;
  justify-content: center;
  align-items: center;
  .login-box {
    width: 300px;
    background: rgba(255, 255, 255, 0.8);
    padding: 60px 40px;
    border-radius: 10px;
    z-index: 100;

    // margin-bottom: 100px;
  }
}
.like-fx {
  position: fixed;
  right: 0;
  z-index: 1;
  pointer-events: none;
  /* background-color: red; */
}
.u-form-item{
  padding-bottom: 10px;
  position: relative;
}
:deep(.u-form-item__body__right__message){
  position: absolute !important;
  bottom: 0px !important;
}
.pos{
  display: none !important;
  position: absolute;
  bottom: 10px;
  color: #666;
  text-decoration: underline;
  left: 0;
  width: 100%;
  height: 30px;
  padding: 0;
  margin: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 12px;
}
</style>
<style lang='scss'>
.versonBox{
  position: fixed;
  bottom: 20px;
  font-size: 10px;
  color: #999;
  width: 100vw;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  .inner{
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .downLoad{
    padding-top: 4px;
    text-decoration: underline;
    color: #165DFF;
    text-underline-offset: 2px;
    font-size: 10px;
  }
}
</style>
